<template>
  <div class="orders">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <h2>我的订单</h2>
          <el-radio-group v-model="currentStatus" @change="handleStatusChange">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button :label="1">已支付</el-radio-button>
            <el-radio-button :label="2">已发货</el-radio-button>
            <el-radio-button :label="3">已完成</el-radio-button>
            <el-radio-button :label="4">已取消</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <div v-if="orders.length === 0" class="empty-orders">
        <el-empty description="暂无订单" />
      </div>
      
      <div v-else class="order-list">
        <div v-for="order in orders" :key="order.orderNo" class="order-item">
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单编号：{{ order.orderNo }}</span>
              <span class="order-time">下单时间：{{ order.createTime }}</span>
            </div>
            <el-tag :type="getOrderStatusType(order.status)">{{ getOrderStatusText(order.status) }}</el-tag>
          </div>
          
          <div class="order-products">
            <div v-for="item in order.orderItems" :key="item.id" class="product-item">
              <img :src="item.productImage" class="product-image">
              <div class="product-info">
                <h3>{{ item.productName }}</h3>
                <p class="product-price">
                  <span class="price">¥{{ item.price }}</span>
                  <span class="quantity">x {{ item.quantity }}</span>
                </p>
              </div>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-amount">
              共 {{ getTotalQuantity(order) }} 件商品，
              总计：<span class="total-price">¥{{ order.totalAmount.toFixed(2) }}</span>
            </div>
            
            <div class="order-actions">
              <el-button
                v-if="order.status === 2"
                type="success"
                @click="handleConfirmReceive(order)"
              >
                确认收货
              </el-button>
              
              <el-button
                v-if="[3, 4].includes(order.status)"
                type="danger"
                @click="handleDeleteOrder(order)"
              >
                删除订单
              </el-button>
              
              <el-button link @click="handleViewDetail(order)">
                查看详情
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="60%"
    >
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ selectedOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(selectedOrder.status)">
              {{ getOrderStatusText(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ selectedOrder.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ selectedOrder.receiver }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedOrder.phone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ selectedOrder.address }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-products">
          <h3>商品信息</h3>
          <el-table :data="selectedOrder.orderItems" style="width: 100%">
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="price" label="单价" width="120">
              <template #default="scope">
                ¥{{ scope.row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="120" />
            <el-table-column label="小计" width="120">
              <template #default="scope">
                ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="detail-footer">
          <div class="amount-info">
            <p>商品总额：¥{{ selectedOrder.totalAmount.toFixed(2) }}</p>
            <p>运费：¥{{ selectedOrder.shippingFee || 0 }}</p>
            <p class="total">实付款：¥{{ ((selectedOrder.totalAmount || 0) + (selectedOrder.shippingFee || 0)).toFixed(2) }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()

// 检查登录状态
if (!userStore.isLoggedIn) {
  ElMessage.warning('请先登录')
  router.push('/login')
}

const currentStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailDialogVisible = ref(false)
const selectedOrder = ref(null)
const orders = ref([])
const loading = ref(false)

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: currentStatus.value || null
    }
    const response = await axios.get('/api/orders/my', { params })
    if (response.data.code === 200) {
      orders.value = response.data.data.list
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

const getOrderStatusType = (status) => {
  const statusMap = {
    1: 'success',
    2: 'warning',
    3: 'success',
    4: 'info',
  }
  return statusMap[status]
}

const getOrderStatusText = (status) => {
  const statusMap = {
    1: '已支付',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status]
}

const getTotalQuantity = (order) => {
  return order.orderItems.reduce((total, item) => total + item.quantity, 0)
}

const handleStatusChange = () => {
  currentPage.value = 1
  fetchOrders()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

const handleConfirmReceive = (order) => {
  ElMessageBox.confirm(
    '确认已收到商品？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.put(`/api/orders/${order.id}/status`, null, {
        params: { status: 3 }
      })
      if (response.data.code === 200) {
        ElMessage.success('已确认收货')
        fetchOrders()
      } else {
        ElMessage.error(response.data.message || '确认收货失败')
      }
    } catch (error) {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败，请稍后再试')
    }
  }).catch(() => {})
}

const handleDeleteOrder = (order) => {
  ElMessageBox.confirm(
    '确定要删除该订单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.delete(`/api/orders/${order.id}`)
      if (response.data.code === 200) {
        ElMessage.success('订单已删除')
        fetchOrders()
      } else {
        ElMessage.error(response.data.message || '删除订单失败')
      }
    } catch (error) {
      console.error('删除订单失败:', error)
      ElMessage.error('删除订单失败，请稍后再试')
    }
  }).catch(() => {})
}

const handleViewDetail = (order) => {
  selectedOrder.value = order
  detailDialogVisible.value = true
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.empty-orders {
  padding: 40px 0;
}

.order-list {
  margin-top: 20px;
}

.order-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.order-header {
  padding: 15px;
  background-color: #f8f8f8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  gap: 20px;
  color: #666;
}

.order-products {
  padding: 15px;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
}

.product-info h3 {
  margin: 0 0 10px 0;
  font-size: 14px;
}

.product-price {
  margin: 0;
  color: #666;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.order-footer {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.order-detail {
  padding: 20px;
}

.detail-products {
  margin-top: 20px;
}

.detail-footer {
  margin-top: 20px;
  text-align: right;
}

.amount-info p {
  margin: 5px 0;
}

.amount-info .total {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
</style> 